import { NgOptimizedImage } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  Provider,
  forwardRef,
  signal,
} from '@angular/core';
import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
} from '@angular/forms';
import { selected } from '@core/animations';

// Adapted from https://github.com/adisreyaj/ng-custom-form-elements/

const CHARACTER_CONTROL_VALUE_ACCESSOR: Provider = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CharacterSelectorComponent),
  multi: true,
};

@Component({
  selector: 'app-character-selector',
  standalone: true,
  providers: [CHARACTER_CONTROL_VALUE_ACCESSOR],
  imports: [NgOptimizedImage],
  templateUrl: './character-selector.component.html',
  styleUrl: './character-selector.component.scss',
  animations: [selected],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CharacterSelectorComponent
  implements ControlValueAccessor
{
  characters = signal([
    '莱欧斯',
    '玛露西尔',
    '齐尔查克',
    '森西',
    '伊津津美',
    '法琳',
  ]);

  selectedCharacter = signal('');
  isDisabled = signal(false);

  private onTouched: any;
  private onChange: any;

  updateCharacterSelection(name: string) {
    this.onTouched && this.onTouched();
    this.selectedCharacter.update((current) =>
      current === name ? '' : name,
    );
    this.onChange &&
      this.onChange(this.selectedCharacter());
  }

  writeValue(value: any): void {
    if (typeof value !== 'string') return;
    if (!this.characters().includes(value)) {
      setTimeout(() => this.onChange && this.onChange(''));
    }

    this.selectedCharacter.set(value);
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState(isDisabled: boolean) {
    this.isDisabled.set(isDisabled);
  }
}

export default CharacterSelectorComponent;
